<?php 
    define("MAX_IDLE_TIME", 3600);
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();//使用session来保存用户会话数据
    /*Session储存用户的服务器地址，用户名，密码
     * Cookies储存当前路径
     * 
     * */
    //定义方法
    function listFTP($url,$username,$password){
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_FTPLISTONLY,false);
        curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//output to memories
        curl_setopt($curl,CURLOPT_HEADER,0);
        $flist = curl_exec($curl);
        curl_close($curl);
        return $flist;
    }
    function downloadFTP($url,$username,$password){
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_FTPLISTONLY,false);
        curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
        curl_exec($curl);
        curl_close($curl);
        exit();
    }
    
    //处理流程
    if (!isset($_SESSION['timeout_idle'])) {
        $_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME;
    } else {
        if ($_SESSION['timeout_idle'] < time()) {
            //destroy session
            session_unset();
        } else {
            $_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME;
        }
    }
    $action = $_REQUEST["action"];
    $url = $_REQUEST['server'];
    $address = "ftp://$url";
    $user = $_REQUEST['user'];
    $pass = $_REQUEST['pass'];
    //根据action处理
    switch ($action){
        case "download":
            header("Content-Type: application/octet-stream");
            $tmpname = preg_replace("/^(.+?\/+?)*/", "", $url);
            header("Content-Disposition: attachment; filename=\"$tmpname\"");
            downloadFTP($address, $user, $pass);
            exit();
            break;
        default:
            echo "no Action";
            break;
    }
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>web ftp filemanager for Nokia n86</title>
</head>
<body>
    <?php
        $flist = listFTP($address,$user,$pass);
        echo $address;
        $flist = str_replace("\r", "", $flist);
        $list = explode("\n", $flist);
        foreach ($list as $filename){
            $itemType = $filename[0];//if start with 'd', there is a directory
            $filename = preg_replace("/[d\-]{1}([a-zA-Z0-9\-:]+?[ ]+?){8}/", "", $filename);
            print "</br><a href=\"?base=/&file=$filename\">";
            print "$filename";
            print "</a>";
        }
	?>
</body>
</html>